package com.itheima.d4_create_thread;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 目标：掌握线程的创建方式三：实现Callable接口。
 */
public class ThreadTest3 {
    public static void main(String[] args) throws Exception {
        //3、创建FutureTask对象，传入Callable子类对象
        Calculator calculator = new Calculator(100);
        FutureTask<Long> futureTask = new FutureTask<>(calculator);

        //4、创建线程对象，传入futureTask任务，调用start方法，开启线程
        Thread t1 = new Thread(futureTask);
        t1.start();

        //5、获取线程的执行结果
        Long rs1 = futureTask.get();
        System.out.println("rs1 = " + rs1);

        //求1～50的和
        FutureTask<Long> ft1 = new FutureTask<>(new Calculator(50));
        new Thread(ft1).start();
        Long rs2 = ft1.get();
        System.out.println("rs2 = " + rs2);
    }
}


//让线程去求1～n的和

//1、创建一个类实现Callable   范型就是结果的类型
class Calculator implements Callable<Long> {
    private long n;

    public Calculator(long n) {
        this.n = n;
    }

    //2、重写call
    @Override
    public Long call() throws Exception {
        long sum = 0;
        for (long i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
}
